package com.cicdi.core.example;

import com.alaya.crypto.CipherException;
import com.alaya.crypto.WalletUtils;
import com.cicdi.core.util.Common;
import com.cicdi.core.util.CsvReaderUtil;
import com.cicdi.core.util.NodeUtil;
import com.cicdi.core.util.SendUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

/**
 * 转账类demo
 *
 * @author haypo
 * @date 2020/12/3
 */
@Slf4j
public class FastSendExample {
    public static void main(String[] args) {
        System.out.println("\n\n-----------------快速转账工具------------------\n");
        System.out.println("请输入节点url(包含端口号，如http://localhost:6789)，若不输入或者输入为空，则使用官方rpc：");
        String nodeUrl = new Scanner(System.in).nextLine();
        if (nodeUrl == null || nodeUrl.trim().isEmpty()) {
            nodeUrl = Common.NODE_URL;
        }
        try {
            if (NodeUtil.testNode(nodeUrl)) {
                log.info("节点连接成功！");
            } else {
                log.error("输入的节点url似乎连不上");
                return;
            }
        } catch (Exception e) {
            log.error("输入的节点url似乎连不上\n" + e.getMessage(), e);
            return;
        }
        SendUtil sendUtil = new SendUtil(nodeUrl);
        try {
            System.out.println("请输入密码:");
            String password = new Scanner(System.in).nextLine();
            System.out.println("请输入钱包路径:");
            String source = new Scanner(System.in).nextLine();
            System.out.println("请输入目的钱包的csv文件路径:");
            String csvFilePath = new Scanner(System.in).nextLine();
            CsvReaderUtil csvReaderUtil = new CsvReaderUtil(csvFilePath, false);
            List<String[]> data = csvReaderUtil.read();
            System.out.println("请输入转账的金额（单位为ATP）:");
            BigDecimal atpAmount = new Scanner(System.in).nextBigDecimal();
            List<String> addressList = data.stream().map(s -> s[0]).collect(Collectors.toList());
            sendUtil.fastSend(WalletUtils.loadCredentials(password, source), addressList, atpAmount);
        } catch (CipherException | IOException e) {
            if (e instanceof CipherException) {
                log.error("可能是钱包密码不对或者钱包json文件格式不对" + e.getMessage(), e);
            } else {
                log.error("io流异常，可能是csv文件路径不对" + e.getMessage(), e);
            }
        }
    }
}
